//
//  OAuthViewController.swift
//  HMWeibo007
//
//  Created by TTang on 15/7/1.
//  Copyright © 2015年 shanyu. All rights reserved.
//

import UIKit
import SVProgressHUD
class OAuthViewController: UIViewController,UIWebViewDelegate {
    //定义常量
    private let  WB_Client_ID      =  "3331539595"
    private let  WB_Redirect_URI   =  "http://www.baidu.com"
    private let  WB_Client_Secret  =  "d51e13b9d586a053a2a0eff1be505071"
    //懒加载webView
    lazy var webView: UIWebView? = {
    
        let v = UIWebView()
        v.delegate = self
        return v
    }()
    
    override func loadView() {
        
        //根视图就是webView
        view = webView
        
        title = "新浪微博"
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        
    }
    //关闭
    func close (){
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    override func viewDidLoad() {
        loadOAuthPage()
    }
    ///  加载授权页面
    private func loadOAuthPage (){
     
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WB_Client_ID)&redirect_uri=\(WB_Redirect_URI)"
        
        let url = NSURL(string: urlString)!
        
        webView?.loadRequest(NSURLRequest(URL: url))
    
    }
    
    // MARK: - 实现UIWebViewDelegate代理方法
    //在 iOS 的开发中，如果代理方法返回 true，表示一切正常，如果返回 false，表示什么也不做
    /**
        初始：
            https://api.weibo.com/oauth2/authorize?client_id=3331539595&redirect_uri=http://www.baidu.com
        登陆成功：
            https://api.weibo.com/oauth2/authorize
        *** 授权成功 - 授权码
            https://www.baidu.com/?code=cbc8144b77d782ada8836c46d29342d6
    
    1> 如果是新浪的 URL，就继续加载
    2> 如果是回调地址，需要根据 URL 中的内容，判断是否有授权码
    */
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
    
        //0.获取完整的URL字符串
        let urlString = request.URL!.absoluteString
        
        //1.如果不是回调地址，则继续
        if !urlString .hasPrefix(WB_Redirect_URI) {
         
            return true
        }
        //2.如果是回调地址，则需要判断是否有授权码
        let query = request.URL!.query!
        //print(query)
        
        let codeStr = "code="
        if query.hasPrefix(codeStr) {
            
            let code = query.substringFromIndex(advance(codeStr.endIndex, 0))
            print("获取授权码\(code)")
            loadAccessToken(code)
        
        }else{
            print("取消授权")
            //关闭窗口
            close()
        }
        
        return true
    }
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    //MARK: - 加载accessToken
    private func loadAccessToken(code:String) {
     
        let urlString = "oauth2/access_token"
        
        let params = ["client_id":WB_Client_ID,
            "client_secret":WB_Client_Secret,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri":WB_Redirect_URI]
     
        
        NetworkTools.sharedNetworkTools().POST(urlString, parameters: params, success: { (_, JSON) -> Void in
           
           // 字典转模型 －> 加载用户信息，链式调用 Alamofire
           UserAccount(dict: JSON as! [String:AnyObject]).loadUserInfo { (account, error) -> () in
                // 判断账户信息是否正确
                if account != nil{
                   print(account)
                   //设置全局的account
                   sharedUserAccount = account
                   //发送通知
                   //这里的false表示登陆成功后进入的不是主界面，而是欢迎界面
                   NSNotificationCenter.defaultCenter().postNotificationName(HMSwitchRootVCNotification, object: false)
                   //关闭控制器
                   self.close()
                    
                   return
                }
                
                print(error)
                SVProgressHUD.showErrorWithStatus("您的网络不给力")
            }
            
            
            }) { (_, error) -> Void in
                print(error)
                SVProgressHUD.showErrorWithStatus("您的网络不给力")
        }
    
    }
    //dealloc
    deinit{
     print("------------>88")
    }
    
    
    
}
